﻿
using UnityEngine;

namespace DanmakuGame
{
    public abstract class ALiveWebSocketBase
    {
        private readonly string _ip = "127.0.0.1";
        private int _port;
        private DanmakuToolWebsocket _ws;

        public ALiveWebSocketBase(int port, bool isSilentReconnect = true)
        {
            _port = port;
            var url = $"ws://{_ip}:{_port}";
            _ws = new DanmakuToolWebsocket(url);
            _ws.IsSilentReconnect = isSilentReconnect;
            _ws.OnOpenEvt = OnOpen;
            _ws.OnErrorEvt = OnError;
            _ws.OnSilentReconnectEvt = OnSilentReconnect;
            _ws.OnReceivedBinaryEvt = OnBinaryReceived;
            _ws.OnReceivedStringEvt = OnMessageReceived;
        }

        protected abstract void OnReceivedBinary(byte[] buffer);
        protected abstract void OnReceivedString(string message);

        public void Connect()
        {
            _ws.Connect();
        }

        public void Disconnect()
        {
            _ws.Disconnect();
        }

        public void Reconnect()
        {
            _ws.Reconnect();
        }

        public void SendMsg(string msg)
        {
            _ws.Request(msg);
        }

        private void OnOpen() 
        {
            Debug.Log($"{GetType().Name} 连接成功...");
        }

        private void OnError() 
        {
            Debug.Log($"{GetType().Name} 连接失败...");
        }

        private void OnSilentReconnect() 
        {
            Debug.Log($"{GetType().Name} 重连中...");
        }

        private void OnBinaryReceived(byte[] buffer)
        {
            OnReceivedBinary(buffer);
        }

        private void OnMessageReceived(string message)
        {
            OnReceivedString(message);
        }

    }
}
